<template>
    <div class="about-container">
        <a-spin tip="Loading..." :spinning="loading">
            <a-card title="员工管理">
                <div class="big-box">
                    <a-row>
                        <a-col :span="6">
                            <div class="left-side">
                                <a-card title="组织架构">
                                    <a-tree :replace-fields="replaceFields" v-model="checkedKeys" :expanded-keys="expandedKeys"
                                        :auto-expand-parent="autoExpandParent" :selected-keys="selectedKeys" :tree-data="treeData"
                                        @expand="onExpand" @select="onSelect" />
                                </a-card>
                            </div>
                        </a-col>
                        <a-col :span="18">
                            <div class="right-side">
                                <a-card>
                                    <div class="right-toolBar">
                                        <a-button type="primary" @click="orgTreeEdit"
                                            v-if="$utilCheckPermission(['staffManagementOCompile'])">编辑</a-button>
                                        <a-button type="primary" @click="removeOrg"
                                            v-if="$utilCheckPermission(['staffManagementORemove'])">删除</a-button>
                                        <a-button type="primary" @click="addOrg"
                                            v-if="$utilCheckPermission(['staffManagementAddJunior'])">添加下级</a-button>
                                    </div>
                                    <a-row style="margin-top: 20px">
                                        <a-col :span="12">
                                            <a-input-search v-model="search" style="width: 235px;" allow-clear placeholder="请搜索"
                                                @search="getTableData"></a-input-search>
                                        </a-col>
                                        <a-col :span="12">
                                            <div style="text-align: right">
                                                <a-button type="primary" @click="add"
                                                    v-if="$utilCheckPermission(['staffManagementAdd'])">添加员工</a-button>
                                            </div>
                                        </a-col>
                                    </a-row>
                                    <a-row style="margin-top: 20px">
                                        <a-table bordered :rowKey="(item,i)=>item.id" :columns="tableOption.columns"
                                            :data-source="tableOption.tableData" :pagination="tableOption.pagination"
                                            :loading="tableOption.loading"></a-table>
                                    </a-row>
                                </a-card>
                            </div>
                        </a-col>
                    </a-row>
                </div>
            </a-card>
        </a-spin>
        <a-modal :width="600" v-model="orgTreeOption.show" :title="orgTreeOption.title" :confirm-loading="orgTreeOption.loading"
            @ok="orgModalOk" cancelText="取消" okText="确定">
            <a-form-model ref="orgForm" :rules="orgTreeOption.rules" :model="orgTreeOption.formData">
                <a-form-model-item label="名称" prop="type">
                    <a-input v-model="orgTreeOption.formData.type" placeholder="请输入名称" />
                </a-form-model-item>
            </a-form-model>
        </a-modal>

        <a-modal width="900px" v-model="modalOption.show" :title="modalOption.title" @ok="ModalOk"
            @cancel="modalOption.pageReady=false" cancelText="取消" okText="确定">
            <a-spin tip="Loading..." :spinning="modalOption.loading">
                <a-form-model layout="inline" class="yuan-form" ref="form" :rules="modalOption.rules"
                    :model="modalOption.formData" :label-col="{ style: { width: '100px' } }"
                    :wrapper-col="{ style: { width: 'calc(100% - 120px)' } }">
                    <div class="form-panel">
                        <div class="form-panel-box yuan-form-col5">
                            <a-form-model-item class="yuan-form-item" label="姓名" prop="name">
                                <a-input class="yuan-form-input" v-model="modalOption.formData.name" placeholder="请输入"></a-input>
                            </a-form-model-item>
                            <!-- <a-form-model-item class="yuan-form-item" label="员工编号" prop="number">
                                <a-input class="yuan-form-input" v-model="modalOption.formData.number"
                                    placeholder="请输入"></a-input>
                            </a-form-model-item> -->

                            <a-form-model-item class="yuan-form-item" label="手机号" prop="phone">
                                <a-input class="yuan-form-input" v-model="modalOption.formData.phone" placeholder="请输入" autocomplete="new-user"></a-input>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item" label="身份证号" prop="idNumber">
                                <a-input class="yuan-form-input" v-model="modalOption.formData.idNumber" autocomplete="new-user"
                                    placeholder="请输入"></a-input>
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-item" label="组织架构" prop="organizationId">
                                <a-tree-select class="yuan-form-input" v-model="modalOption.formData.organizationId"
                                    @select="treeSelect" :replaceFields="replaceFields" :tree-data="treeData" placeholder="请选择" />
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-item" label="登录密码" v-if="modalOption.formData.id"
                                prop="haspassword">
                                <a-input class="yuan-form-input" v-model="modalOption.formData.password" placeholder="请输入"
                                    type="password" disabled></a-input>
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-item" style="width:100%" label="登录密码" prop="password" v-else>
                                <a-input class="yuan-form-input" v-model="modalOption.formData.password" placeholder="请输入"
                                    type="password" autocomplete="new-password"></a-input>
                                <span style="margin-left:5px">密码限制8位以上且必须包含大小写字母、数字和特殊符号</span>
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-item" label="状态" prop="status">
                                <a-radio-group v-model="modalOption.formData.status"
                                    :options="[{ 'label': '启用', value: 0 }, { 'label': '禁用', value: 1 }]" :default-value="0" />
                            </a-form-model-item>
                            <div class="clear-both"></div>
                            <a-form-model-item label="员工头像" class="yuan-form-item" v-if="modalOption.pageReady">
                                <Upload :uploadLength="1" @uploadChange="uploadChangeHead"
                                    :defImgList="modalOption.formData.headPortrait?[modalOption.formData.headPortrait]:[]" />
                                <div class="upload-tips">jpg.png.gif格式.不超过2MB</div>
                            </a-form-model-item>
                        </div>
                    </div>
                </a-form-model>
            </a-spin>
        </a-modal>
    </div>
</template>

<script>
import { h } from "vue";
import api from "@/api/api";
import Upload from "@/components/upload.vue";
import { downLoadFile } from "@/utils/index";

export default {
    name: "memberManagement",
    components: { Upload },
    data() {
        return {
            loading: false,
            replaceFields: { title: "name", key: "id", value: "id", children: "children" },
            expandedKeys: [],
            autoExpandParent: true,
            checkedKeys: [],
            selectedKeys: [],
            treeData: [],
            search: "",
            curNode: {
                type: "",
                id: "",
            },
            orgTreeOption: {
                show: false,
                title: "",
                loading: false,
                rules: {
                    type: [{ required: true, message: "请输入名称", trigger: "blur" }],
                },
                formData: {
                    type: "",
                    id: "",
                    parentId: "",
                },
            },
            tableOption: {
                columns: [
                    {
                        title: "姓名",
                        dataIndex: "name",
                        key: "name",
                    },
                    // {
                    //     title: "员工编码",
                    //     dataIndex: "number",
                    //     key: "number",
                    // },
                    {
                        title: "组织架构",
                        dataIndex: "organizationName",
                        key: "organizationName",
                    },
                    // {
                    //     title: "状态",
                    //     dataIndex: "status",
                    //     key: "status",
                    //     customRender: (text, record, index) => {
                    //         return h(
                    //             "div",
                    //             { class: record.status === 0 ? "c-success" : "c-danger" },
                    //             record.status === 0 ? "启用" : "禁用"
                    //         );
                    //     },
                    // },
                    {
                        title: "操作",
                        width: 280,
                        customRender: (text, record, index) => {
                            const editBtn = h(
                                "a-button",
                                {
                                    style: { marginRight: "10px" },
                                    props: { icon: "edit", type: "primary", size: "small" },
                                    on: { click: () => this.edit(record) },
                                },
                                "编辑"
                            );
                            // const statusBtn = h(
                            //     "a-button",
                            //     {
                            //         style: { marginRight: "10px" },
                            //         props: { icon: "edit", type: record.status === 0 ? "danger" : "primary", size: "small" },
                            //         on: { click: () => this.changeMemberStatus(record) },
                            //     },
                            //     record.status === 0 ? "禁用" : "启用"
                            // );

                            const deleteBtn = h(
                                "a-popconfirm",
                                {
                                    props: { title: "删除？", okText: "确定", cancelText: "取消" },
                                    on: { confirm: () => this.deleteMember(record) },
                                },
                                [h("a-button", { props: { icon: "delete", type: "danger", size: "small" } }, "删除")]
                            );
                            const btn = [];
                            if (this.$utilCheckPermission(["staffManagementCompile"])) btn.push(editBtn);
                            //if (this.$utilCheckPermission(["staffManagementForbidden"])) btn.push(statusBtn);
                            if (this.$utilCheckPermission(["staffManagementRemove"])) btn.push(deleteBtn);
                            return h("div", { style: { display: "flex", justifyContent: "center" } }, btn);
                        },
                    },
                ],
                tableData: [],
                pagination: {
                    pageSize: 10,
                    current: 1,
                    total: 0,
                    showTotal: (total) => `共${total}条`,
                    onChange: (page, pageSize) => this.PageChange(page, pageSize),
                },
                loading: false,
            },
            modalOption: {
                pageReady: false,
                members: [],
                show: false,
                title: "新增",
                loading: false,
                rules: {
                    name: [{ required: true, message: "请输入名称", trigger: "blur" }],
                    number: [{ required: true, message: "请输入员工编号", trigger: "change" }],
                    organizationId: [{ required: true, message: "请选择组织架构", trigger: "change" }],
                    password: [{ required: true, message: "请输入密码", trigger: "change" }],
                    phone: [{ required: true, message: "请输入手机号", trigger: "change" }],
                },
                formData: {
                    phone: "",
                    username: "",
                    typeId: "",
                },
            },
        };
    },
    watch: {
        "modalOption.show"(val) {
            if (!val) {
                this.$refs.form.resetFields();
            }
        },
    },
    mounted() {
        this.getRootData();
        this.getTableData();
    },
    methods: {
        async getTableData() {
            this.tableOption.loading = true;
            let params = {
                organizationId: this.curNode.id,
                pageSize: this.tableOption.pagination.pageSize,
                pageNum: this.tableOption.pagination.current,
                name: this.search,
            };
            try {
                const res = await api.getAccountList(params);
                const data = res.data;
                console.info(data);
                if (data && data.rows && data.total) {
                    this.tableOption.tableData = data.rows;
                    this.tableOption.pagination.total = data.total;
                } else {
                    this.tableOption.tableData = [];
                }
            } finally {
                this.tableOption.loading = false;
            }
        },
        removeOrg() {
            if (this.curNode.id === "3a3bafbe4be36ca7fa9858b55687de4b") {
                this.$message.error("顶级组织不可以删除");
                return;
            }
            if (this.curNode.id) {
                this.$confirm({
                    title: "确定要删除吗？",
                    content: "删除后无法恢复",
                    okText: "确定",
                    cancelText: "取消",
                    onOk: async () => {
                        const res = await api.deleteOrganization(this.curNode.id);
                        this.$message.success(res.msg);
                        this.curNode = {};
                        this.getRootData();
                        this.getTableData();
                    },
                    onCancel: () => {
                        console.log("Cancel");
                    },
                });
            } else {
                this.$message.error("请选择一个节点");
            }
        },
        async deleteMember(record) {
            try {
                this.loading = true;
                const res = await api.deleteAccount(record.userId);
                this.$message.success(res.msg);
                this.getTableData();
            } finally {
                this.loading = false;
            }
        },
        async changeMemberStatus(record) {
            this.$confirm({
                title: "确定要修改状态吗？",
                okText: "确定",
                cancelText: "取消",
                onOk: async () => {
                    const res = await api.updateAccount({
                        id: record.userId,
                        status: record.status === 0 ? 1 : 0,
                    });
                    this.$message.success(res.msg);
                    this.getTableData();
                },
                onCancel: () => {
                    console.log("Cancel");
                },
            });
        },
        addOrg() {
            if (this.curNode.id) {
                this.orgTreeOption.show = true;
                this.orgTreeOption.title = "新增";
            } else {
                this.$message.error("请选择一个节点");
            }
        },
        orgTreeEdit() {
            if (this.curNode.id === "3a3bafbe4be36ca7fa9858b55687de4b") {
                this.$message.error("顶级组织不可以编辑");
                return;
            }
            if (this.curNode.id) {
                this.orgTreeOption.show = true;
                this.orgTreeOption.title = "编辑";
                this.orgTreeOption.formData = {
                    type: this.curNode.name,
                    id: this.curNode.id,
                    parentId: this.curNode.parentId,
                };
            } else {
                this.$message.error("请选择一个节点");
            }
        },
        async getRootData() {
            this.loading = true;
            try {
                // 获取顶级架构
                const res = await api.getOrganizationList("3a3bafbe4be36ca7fa9858b55687de4b");
                this.treeData = res.data;
            } finally {
                this.loading = false;
            }
        },
        add() {
            this.modalOption.show = true;
            this.modalOption.title = "新增";
            this.modalOption.formData = { status: 0 };
            this.modalOption.pageReady = true;
        },
        async edit(item) {
            this.modalOption.show = true;
            this.modalOption.title = "编辑";
            this.modalOption.loading = true;
            const res = await api.getAccountDetail(item.userId);
            this.modalOption.formData = { ...res.data };
            this.modalOption.loading = false;
            this.modalOption.pageReady = true;
        },
        orgModalOk() {
            this.orgTreeOption.loading = true;
            this.$refs.orgForm.validate(async (valid) => {
                if (valid) {
                    let params;
                    if (this.orgTreeOption.title == "编辑") {
                        params = {
                            id: this.curNode.id,
                            name: this.orgTreeOption.formData.type,
                        };
                    } else {
                        params = {
                            name: this.orgTreeOption.formData.type,
                            parentId: this.curNode.id,
                        };
                    }
                    const res = await api.editOrganization(params);
                    this.$message.success(res.msg);
                    this.orgTreeOption.show = false;
                    this.getRootData();
                }
                this.orgTreeOption.loading = false;
            });
        },
        ModalOk() {
            this.$refs.form.validate(async (valid) => {
                if (valid) {
                    this.modalOption.loading = true;
                    try {
                        if (!this.modalOption.formData.id) {
                            // 验证密码格式
                            const minLength = 8;
                            const hasNumber = /\d/;
                            const hasSymbol = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
                            const hasLowercase = /[a-z]/;
                            const hasUppercase = /[A-Z]/;
                            const password = this.modalOption.formData.password;
                            if (password.length < minLength) {
                                this.$message.warning("密码长度至少8位");
                                return false;
                            }
                            if (!hasNumber.test(password)) {
                                this.$message.warning("密码必须包含数字");
                                return false;
                            }
                            if (!hasSymbol.test(password)) {
                                this.$message.warning("密码必须包含特殊符号");
                                return false;
                            }
                            if (!hasLowercase.test(password)) {
                                this.$message.warning("密码必须包含小写字母");
                                return false;
                            }
                            if (!hasUppercase.test(password)) {
                                this.$message.warning("密码必须包含大写字母");
                                return false;
                            }
                        }
                        const res = await api.editAccount({
                            ...this.modalOption.formData,
                        });
                        this.$message.success(res.msg);
                        this.modalOption.show = false;
                        this.getTableData();
                    } finally {
                        this.modalOption.loading = false;
                        this.modalOption.pageReady = false;
                    }
                }
            });
        },
        treeSelect(value, node, extra) {
            this.modalOption.formData.type = extra.node.dataRef.type;
        },
        onExpand(expandedKeys) {
            console.log("onExpand", expandedKeys);
            this.expandedKeys = expandedKeys;
            this.autoExpandParent = false;
        },
        onSelect(selectedKeys, info) {
            console.log("selected:", info.node);
            this.selectedKeys = selectedKeys;
            this.curNode.name = info.node.dataRef.name;
            this.curNode.id = info.node.dataRef.id;
            this.curNode.parentId = info.node.dataRef.parentId;

            this.getTableData();
        },
        PageChange(page, pageSize) {
            this.tableOption.pagination.current = page;
            this.getTableData();
        },
        uploadChangeHead(e) {
            this.modalOption.formData.headPortrait = e.length ? e[0].url : "";
        },
    },
};
</script>
<style scoped lang="scss">
.about-container {
    padding: 20px;
    overflow: auto;
    .big-box {
        .left-side {
            margin-right: 20px;
        }
        .right-side {
            .right-toolBar {
                button {
                    margin-right: 10px;
                }
            }
        }
    }
}
</style>
